import React, { useEffect, useState } from 'react';
import { Button, Drawer, Form, Space, message } from 'antd';
import FormRender from '@/components/FormRender';
import { setReceiveInfo } from '@/api';

interface Props {
  callback: () => void;
}

export default function useReceiveModal({ callback }: Props) {
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [employeeId, setEmployeeId] = useState<number>();

  const formList = [
    {
      title: '',
      Items: [
        {
          label: '接单状态',
          name: 'receiveStatus',
          type: 'radio',
          rules: [{ required: true }],
        },
        {
          label: '接单优先级',
          name: 'receivePriority',
          type: 'input',
          rules: [
            { required: true },
            { pattern: /^[0-9]$|^10$/, message: '请输入0-10之间的整数' }
          ],
        },
      ],
    },
  ];
  const onClose = () => {
    form.resetFields();
    setOpen(false);
  };

  const openReceiveModal = (data) => {
    setOpen(true);
    setEmployeeId(data?.employeeId);

    const editItem = {
      receiveStatus: data?.receiveStatus === 'ENABLE',
      receivePriority: data?.receivePriority,
    }
    setTimeout(() => form?.setFieldsValue(editItem), 0);
  };

  const submit = async () => {
    const values = await form.validateFields();
    if (!values) return;
    setLoading(true);
    const params = {
      employeeId,
      receiveStatus: values?.receiveStatus === true ? 'ENABLE' : 'DISABLE',
      receivePriority: values?.receivePriority
    };
    setReceiveInfo(params)
      .then((data) => {
        setLoading(false);
        if (!data) return;
        message.success('编辑成功');
        callback?.();
        onClose();
      })
      .catch((err) => {
        throw err;
      });
  };

  const receiveModal = (
    <Drawer
      title='编辑接单状态'
      width={720}
      onClose={onClose}
      open={open}
      extra={
        <Space>
          <Button onClick={onClose}>关闭</Button>
          <Button onClick={submit} type='primary' loading={loading}>
            提交
          </Button>
        </Space>
      }
    >
      <FormRender form={form} formItem={formList || []} />
    </Drawer>
  );

  return [openReceiveModal, receiveModal];
}
